package com.xu.service.impl;

import com.xu.dao.GoodDao;
import com.xu.dao.SaleDao;
import com.xu.exce.NotEnoughException;
import com.xu.pojo.Goods;
import com.xu.pojo.Sale;
import com.xu.service.BuyGoodsService;
import org.apache.ibatis.annotations.Param;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class BuyGoodsServiceImpl implements BuyGoodsService {
    private GoodDao goodDao;
    private SaleDao saleDao;

    public void setGoodDao(GoodDao goodDao) {
        this.goodDao = goodDao;
    }

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }

    /**
     * @Transactional 使用的是AOP织入，环绕通知机制。
     * 有默认值    @Transactional(propagation = Propagation.REQUIRED,
     *             isolation = Isolation.DEFAULT,
     *             readOnly = false,
     *             rollbackFor = {NotEnoughException.class,NullPointerException.class})
     *
     *             如果异常是以上rollbackFor中的异常或者运行时异常就会回滚
     * 以上等同于@Transaction
     */
/*    @Transactional(propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            readOnly = false,
            rollbackFor = {NotEnoughException.class,NullPointerException.class})*/
    @Override
    public void buy(@Param("gid") Integer goodId, Integer nums) {
        System.out.println("=====buy方法的开始=====");
        //记录销售信息
        Sale sale = new Sale();
        sale.setGid(goodId);
        sale.setNums(nums);
        int i = saleDao.insertSale(sale);
        //更新库存
        Goods goods = goodDao.selectGood(goodId);
        if (goods == null) {
            throw new NotEnoughException("无此商品");
        }
        if (goods.getAmount() < nums ) {
            throw new NotEnoughException("库存不足");
        }
        goods = new Goods();
        goods.setAmount(nums);
        goods.setId(goodId);
        goodDao.updateGood(goods);
        System.out.println("=====buy方法的结束=====");


    }
}
